package com.totcy.atom.view.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.totcy.atom.BuildConfig;
import com.totcy.atom.CommonValues;
import com.totcy.atom.R;
import com.totcy.atom.adapter.MineMenuAdapter;
import com.totcy.atom.bean.DailySentenceCiBa;
import com.totcy.atom.bean.MineMenuModel;
import com.totcy.atom.bean.User;
import com.totcy.atom.presenter.DailySentencePresenter;
import com.totcy.atom.presenter.contract.DailySentenceContract;
import com.totcy.atom.utils.UserUtil;
import com.totcy.atom.view.activity.LoginActivity;
import com.totcy.atom.view.activity.OldAlmanacActivity;
import com.totcy.atom.view.activity.PersonalCenterActivity;
import com.totcy.atom.view.activity.PictureBrowsingActivity;
import com.totcy.atom.view.activity.WeatherActivity;
import com.totcy.atom.view.activity.WebViewActivity;
import com.totcy.baselibrary.adapter.BaseLoadMoreAdapter;
import com.totcy.baselibrary.adapter.divider.RecycleViewDivider;
import com.totcy.baselibrary.dialog.ActionSheetDialog;
import com.totcy.baselibrary.utils.DataCleanManager;
import com.totcy.baselibrary.utils.SPUtil;
import com.totcy.baselibrary.utils.StatusBarUtil;
import com.totcy.baselibrary.utils.TakePhoto;
import com.totcy.baselibrary.utils.ToastUtil;
import com.totcy.baselibrary.widget.guideview.Component;
import com.totcy.baselibrary.widget.guideview.Guide;
import com.totcy.baselibrary.widget.guideview.GuideBuilder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * description: 主页我的
 *
 * @author : Totcy
 * date: 2017/10/31 17:34
 * update: 2017/10/31
 */

public class HomeMineFragment extends BaseFragment implements TakePhoto.OnSelectUriListener, BaseLoadMoreAdapter.OnItemClickListener, MineMenuAdapter.UserInfoClickListener, Toolbar.OnMenuItemClickListener, DailySentenceContract.View {

    private static final String TAG = "HomeMineFragment";

    public static final String USER_IMG = "userImg";
    private static final String FIRST_GUIDE_USER_IMG = "first_set_user_img";

    @BindView(R.id.rv_mineMenuList)
    RecyclerView rvMenuList;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private TakePhoto takePhoto;
    private User user;
    private MineMenuAdapter menuAdapter;
    private List<MineMenuModel> menuModelList = new ArrayList<>();

    private DailySentencePresenter dailySentencePresenter;
    private DailySentenceCiBa dailySentenceCiBa;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home_mine;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        //fragment自己适配 toolbar 增加title layout paddingTop
        StatusBarUtil.setPaddingSmart(getActivity(), toolbar);

        takePhoto = new TakePhoto(this, getActivity(), true, BuildConfig.AUTHORITIES);
        takePhoto.setOnSelectUriListener(this);
        initMenu();

        dailySentencePresenter = new DailySentencePresenter(getActivity());
        dailySentencePresenter.attachView(this);
    }

    private void initMenu() {
        LinearLayoutManager lm = new LinearLayoutManager(getActivity());
        lm.setOrientation(LinearLayoutManager.VERTICAL);
        rvMenuList.setLayoutManager(lm);
        menuAdapter = new MineMenuAdapter(getActivity(), menuModelList, this,
                LayoutInflater.from(getActivity()).inflate(R.layout.header_mine_user_info, rvMenuList, false));
        menuAdapter.setOnItemClickListener(this);

        rvMenuList.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, (int) (getResources().getDisplayMetrics().density * 0.5),
                ContextCompat.getColor(getActivity(), R.color.cut_line_color))
                .setDrawTop(false));

        //用户信息
        user = UserUtil.getInstances().getUserInfo();
        //读取保存的头像
        if (!TextUtils.isEmpty((String) SPUtil.get(getActivity(), USER_IMG, ""))) {
            user.setUserImage((String) SPUtil.get(getActivity(), USER_IMG, ""));
        }
        //添加了菜单后再 notifyDataSetChanged，避免baseLoadMoreAdapter中 由于数据改变 导致类型转换出错。
        //initMenuList()中添加了数据
        menuAdapter.setUserInfo(user);
        //设置右上角菜单
        toolbar.inflateMenu(R.menu.menu_mine);
        toolbar.setOnMenuItemClickListener(this);

        initMenuList();
    }

    @SuppressLint("CheckResult")
    private void initMenuList() {

        Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                menuModelList.clear();
                menuModelList.add(new MineMenuModel(R.drawable.ic_delete_black_20dp, getString(R.string.clear_cache) + "(" + getFormatCacheSize() + ")"));
                menuModelList.add(new MineMenuModel(R.drawable.ic_brightness_3_black_20dp, getString(R.string.night_model)));
                menuModelList.add(new MineMenuModel(R.drawable.ic_face_black_20dp, getString(R.string.about_us)));
                menuModelList.add(new MineMenuModel(R.drawable.ic_today_black_20dp, getString(R.string.daily_sentence)));
                menuModelList.add(new MineMenuModel(R.drawable.ic_cloud_black_20dp, getString(R.string.mine_menu_weather)));
                menuModelList.add(new MineMenuModel(R.drawable.ic_exit_to_app_black_20dp, getString(R.string.logout)));
                e.onNext("");
            }
        })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
                        rvMenuList.setAdapter(menuAdapter);
                        rvMenuList.post(new Runnable() {
                            @Override
                            public void run() {
                                showGuideView();
                            }
                        });
                    }
                });
    }

    /**
     * 读取缓存
     */
    @SuppressLint("CheckResult")
    private void loadAppCache() {
        if (menuModelList.size() > 0) {
            Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(ObservableEmitter<String> e) throws Exception {
                    menuModelList.get(0).setMenuName(getString(R.string.clear_cache) + "(" + getFormatCacheSize() + ")");
                    e.onNext("");
                }
            })
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(@NonNull String s) throws Exception {
                            menuAdapter.notifyDataSetChanged();
                        }
                    });
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // 读取缓存
        if (!isHidden()) {
            loadAppCache();
        }
    }

    @Override
    public void onItemClick(int position) {
        Bundle bundle;
        switch (position) {

            case 0:
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.do_you_clear_the_cache)
                        .setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                clearCache();
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create()
                        .show();

                break;
            case 1:
                ToastUtil.showToast(getActivity(), "待开发");
                break;
            case 2:
                bundle = new Bundle();
                bundle.putString("url", CommonValues.PROJECT_FROM_MAYUN_URL);
                bundle.putString("title", BuildConfig.APP_NAME);
                openActivity(WebViewActivity.class, bundle);
                break;
            case 3:
                if (dailySentenceCiBa == null) {
                    dailySentencePresenter.getDailySentence();
                } else {
                    lookDailySentence();
                }

                break;
            case 4:
                //天气
                openActivity(WeatherActivity.class);
                break;
            case 5:
                //退出登录
                new AlertDialog.Builder(getActivity())
                        .setMessage(R.string.did_you_log_out)
                        .setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UserUtil.getInstances().removeUserInfo();
                                dialog.dismiss();
                                getActivity().finish();
                                openActivity(LoginActivity.class);
                            }
                        })
                        .setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create()
                        .show();


                break;
            default:
                break;

        }
    }

    /**
     * 查看每日一句
     */
    private void lookDailySentence() {
        ArrayList<String> urlList = new ArrayList<>();
        urlList.add(dailySentenceCiBa.getFenxiang_img());
        Bundle bundle = new Bundle();
        bundle.putInt("position", 0);
        bundle.putStringArrayList("urlList", urlList);
        openActivity(PictureBrowsingActivity.class, bundle);
    }

    /**
     * 清除缓存
     */
    @SuppressLint("CheckResult")
    private void clearCache() {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                DataCleanManager.cleanExternalCache(getActivity());
                DataCleanManager.cleanInternalCache(getActivity());
                SPUtil.put(getActivity(), USER_IMG, "");
                menuModelList.get(0).setMenuName(getString(R.string.clear_cache) + "(" + getFormatCacheSize() + ")");
                e.onNext("");
            }
        })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
                        menuAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void showSelectImgDialog() {

        new ActionSheetDialog(getActivity())
                .setSheetItem(getResources().getStringArray(R.array.select_photo), new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        if (which == 0) {
                            takePhoto.userCamera();
                        } else {
                            takePhoto.openAlbum();
                        }
                    }
                })
                .builder()
                .show();
    }

    @Override
    public void onUserInfoClick() {

        openActivity(PersonalCenterActivity.class);

    }

    @SuppressLint("CheckResult")
    @Override
    public void onHeadImgSelect() {
        new RxPermissions(getActivity())
                .request(Manifest.permission.CAMERA
                        , Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            showSelectImgDialog();
                        }
                    }
                });
    }

    @Override
    public void onSelectResult(Uri result) {
        //保存设置的头像
        SPUtil.put(getActivity(), USER_IMG, result.toString());
        user.setUserImage(result.toString());
        menuAdapter.updateUserInfo(user);
        //刷新缓存
        loadAppCache();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePhoto.attachToActivityForResult(requestCode, resultCode, data);
    }

    /**
     * 创建引导层
     */
    private void showGuideView() {
        boolean firstLook = (boolean) SPUtil.get(getActivity(), FIRST_GUIDE_USER_IMG, true);
        if (!firstLook) {
            return;
        }
        Guide guide = new GuideBuilder()
                .setTargetView(menuAdapter.getHeaderViewHolder().itemView)
                .setAlpha(150)
                //.setHighTargetCorner(10)
                //.setHighTargetPadding(5)
                .setOverlayTarget(false)
                .setOutsideTouchable(false)
                .setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        SPUtil.put(getActivity(), FIRST_GUIDE_USER_IMG, false);
                    }
                })
                .addComponent(new SimpleComponent())
                .createGuide();
        guide.setShouldCheckLocInWindow(false);
        guide.show(getActivity());

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        openActivity(OldAlmanacActivity.class);
        return true;
    }

    @Override
    public void onDailySentenceCiBa(DailySentenceCiBa dailySentenceCiBa) {
        this.dailySentenceCiBa = dailySentenceCiBa;
        lookDailySentence();
    }

    @Override
    public void onDataFail(int code, String message) {

    }

    private class SimpleComponent implements Component {

        @Override
        public View getView(LayoutInflater inflater) {
            return inflater.inflate(R.layout.guide_layout_mine_user_info, null);
        }

        @Override
        public int getAnchor() {
            return Component.ANCHOR_BOTTOM;
        }

        @Override
        public int getFitPosition() {
            return Component.FIT_START;
        }

        @Override
        public int getXOffset() {
            return 5;
        }

        @Override
        public int getYOffset() {
            return 10;
        }
    }

    /**
     * 获取格式化后的缓存大小
     *
     * @return
     */
    private String getFormatCacheSize() {
        try {
            return DataCleanManager.getFormatSize(
                    DataCleanManager.getFolderSize(getActivity().getExternalCacheDir()) +
                            DataCleanManager.getFolderSize(getActivity().getCacheDir())
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0Byte";
    }

}
